﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FluentData;
using HtmlAgilityPack;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using TaoBaoKe.Common;
namespace htmlTBK
{
    public partial class GetKeyFromBD : System.Web.UI.Page
    {
        bool fuckingBD = true;
        public int timer = 2 * 1000;
        IDbContext dbContext = new DbContext().ConnectionString("server=.;User ID=sa;Password=111111;database=test;Connection Reset=FALSE", new SqlServerProvider());
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!fuckingBD)
            {
                return;
            }
            string keySeed = this.lblSeed.Text;
            keySeed = keySeed.Replace("2010", "").Replace("2011", "").Replace("2012", "").Replace("2009", "");
            if (String.IsNullOrEmpty(keySeed))
            {
                Response.Write("么有关键字");
                return;
            }
            keySeed = Server.UrlEncode(keySeed);//不编码有些字符百度会报错== 如&
            HtmlWeb w = new HtmlWeb();
            w.OverrideEncoding = Encoding.UTF8;
            w.UseCookies = true;
            w.NeedParse = false;
            w.PostData = "path=GET%2Fkr%2Fword&userid="+this.tbuserid.Text+"&token=" + this.tbData.Text.Trim() + "&params={\"logid\":1281158721,\"planid\":0,\"unitid\":0,\"entry\":\"kr_tools\",\"query\":\"" + keySeed + "\",\"regions\":\"\",\"rgfilter\":1,\"device\":\"0\",\"querytype\":1}";
            w.CookieStr =this.tbCookies.Text.Trim().Replace(";", ",");
            w.PreRequest += req;
            HtmlDocument d = w.Load("http://fengchao.baidu.com/nirvana/request.ajax?path=GET/kr/word", "post");
            string result = d.Text;
            if (result.Contains("user query too freq")||!result.Contains("\"status\":200"))
            {
                fuckingBD = false;
                Response.Write("百度已经检测到恶意查询,稍后再试");
                timer = 1000 * 60 * 2;
                this.lblErrorInfo.Text = result;
                return;
            }
            else
            {
                this.lblErrorInfo.Text = "";
            }
            MatchCollection mc = result.Matches("word\":\"(?<text>.*?)\"");
            this.lblResult.Text = "";
            for (int i = 0; i < mc.Count;i++ )
            {
                this.lblResult.Text += "," + mc[i].Groups["text"].Value;
            }
        }

        private bool req(System.Net.HttpWebRequest request)
        {
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Origin", "http://fengchao.baidu.com");
            request.AutomaticDecompression = DecompressionMethods.GZip;
            request.Host = "fengchao.baidu.com";
            request.Referer = "http://fengchao.baidu.com/nirvana/main.html?userid=6144127";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
            return true;
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            if (!fuckingBD)
            {
                return;
            }
            //server=192.168.9.1\sql2005;User ID=datauser;Password=datauser;database=FOF;Connection Reset=FALSE
            //Data Source={0};Pooling=true;FailIfMissing=false;UTF8Encoding=True;
            Models.tbk_Keyword m = dbContext.Sql("select top 1 * from tbk_Keyword  where  IsUsed=0").QuerySingle<Models.tbk_Keyword>();
            if (m != null)
            {
                this.lblSeed.Text = m.Keyword;
                this.lblId.Text = m.KeywordId.ToString();
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            if (!fuckingBD)
            {
                return;
            }
            string[] keys = this.lblResult.Text.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
            int seed = Convert.ToInt32(this.lblId.Text);
            int js = 0;
            for (int i = 0; i < keys.Length; i++)
            {
                //if (dbContext.Sql("select count(1) from tbk_KeywordBySeed where Keyword='" + keys[i].Replace("'", "") + "'").QuerySingle<int>() > 0)
                //{
                //    //Response.Write("发现重复数据<br/>");
                //    continue;
                //}
                Models.tbk_KeywordBySeed k=new Models.tbk_KeywordBySeed();
                k.Keyword=keys[i];
                k.SeedId=seed;
                dbContext.Insert<Models.tbk_KeywordBySeed>("tbk_KeywordBySeed", k).AutoMap(x => x.Kid).Execute();
                js++;
            }
            if (js==0)
            {
                Models.tbk_KeywordBySeed k = new Models.tbk_KeywordBySeed();
                k.Keyword =this.lblSeed.Text;
                k.SeedId = seed;
                dbContext.Insert<Models.tbk_KeywordBySeed>("tbk_KeywordBySeed", k).AutoMap(x => x.Kid).Execute();
            }
            dbContext.Sql("update tbk_keyword set isused=1 where KeywordId=" + seed).Execute();
            Response.Write("插入完成,插入"+js+"条<br/>");
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            try
            {
                int g = Convert.ToInt32(this.TextBox1.Text.Trim());
                for (int i = 0; i < g; i++)
                {
                    if (!fuckingBD)
                    {
                        return;
                    }
                    this.Button3_Click(null, null);
                    this.Button1_Click(null, null);
                    this.Button2_Click(null, null);
                }
                dbContext.Dispose();
            }
            catch (Exception ex)
            {
                this.lblError.Text += ex.Message;
            }
           
        }

        protected void TextBox3_TextChanged(object sender, EventArgs e)
        {

        }

        protected void tbCookies_TextChanged(object sender, EventArgs e)
        {

        }


    }
}